from sc_engine.apps import messages as msgs
from sc_engine.scrape.service import get_proleague_matches

def make_app(app_name, root_config, config):
    app = ProleagueScheduleFetchApp(get_proleague_matches)

    return {
        msgs.ProleagueFetchRequested: app.proleague_fetch_requested,
    }

class ProleagueScheduleFetchApp(object):
    """Fetch proleague schedules from the kespa web site."""

    def __init__(self, match_fetcher):
        self.match_fetcher = match_fetcher

    def proleague_fetch_requested(self, msg):
        results = self.match_fetcher(msg.date)

        if results is None:
            return

        output = []

        league = results['league']
        date_played = results['date_played']

        for match in results['matches']:
            new_msg = self._message_for_match(league, date_played, match)
            output.append(new_msg)

            for index, game in enumerate(match['games']):
                game_number = index + 1

                new_msg = self._message_for_game(league, date_played,
                        match, game, game_number)


                output.append( new_msg )

        return output
    
    def _message_for_match(self, league, date_played, match):
        return msgs.ProleagueMatchFetchAnnouncement(
            league, match['stage'],
            match['team_one'], match['team_two'],
            date_played,
            match['winner'], match['winner_score'], match['loser_score'])
            

    def _message_for_game(self, league, date_played, match, game, game_number):
        return msgs.ProleagueGameFetchAnnouncement(
            league, match['stage'],
            match['team_one'], match['team_two'],
            date_played,
            game_number, game['map'],
            game['player_one'], game['player_one_start_location'],
            game['player_two'], game['player_two_start_location'],

            game['winner'], game['playtime']
        )

